<?php

declare (strict_types=1);

namespace app\store\controller;

use app\common\exception\BaseException;
use app\store\model\Category as CategoryModel;
use app\store\model\Goods as GoodsModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Exception;
use think\response\Json;

/**
 * 商品管理控制器
 * Class Goods
 * @package app\store\controller
 */
class Goods extends Controller
{
    /**
     * 商品列表
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function list(): Json
    {
        // 获取列表记录
        $model = new GoodsModel;
        $list  = $model->getList($this->request->param());
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 根据商品ID集获取列表记录
     * @param array $goodsIds
     * @return Json
     */
    public function listByIds(array $goodsIds): Json
    {
        // 获取列表记录
        $model = new GoodsModel;
        $list  = $model->getListByIds($goodsIds);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 商品详情
     * @param int $goodsId
     * @return Json
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \cores\exception\BaseException
     */
    public function detail(int $goodsId): Json
    {
        // 获取商品详情
        $model     = new GoodsModel;
        $goodsInfo = $model->getDetail($goodsId);
        return $this->renderSuccess(compact('goodsInfo'));
    }

    /**
     *批量添加商品
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \cores\exception\BaseException
     */
    public function add(): Json
    {
        $params = $this->postForm();
        $model = new GoodsModel;
        if ($model->adds($params)) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 编辑商品
     * @param int $goodsId
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \cores\exception\BaseException
     */
    public function edit(int $goodsId): Json
    {
        // 商品详情
        $model = GoodsModel::detail($goodsId);
        // 更新记录
        if ($model->edit($this->postForm())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 修改商品状态(上下架)
     * @param array $goodsIds 商品id集
     * @param bool $state 为true表示上架
     * @return Json
     */
    public function state(array $goodsIds, bool $state): Json
    {
        $model = new GoodsModel;
        if (!$model->setStatus($goodsIds, $state)) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 删除商品
     * @param array $goodsIds
     * @return Json
     */
    public function delete(array $goodsIds): Json
    {
        $model = new GoodsModel;
        if (!$model->setDelete($goodsIds)) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * @return Json
     * @throws Exception
     */
    public function import(): Json
    {
        $params = $this->postForm();
        if (!isset($params['file']) || empty($params['file'])) {
            return $this->renderSuccess('请先上传文件');
        }
        $filePath = app()->getRootPath() . 'public/uploads/' . $params['file'];
        if (!file_exists($filePath)) {
            return $this->renderSuccess('文件不存在');
        }
        $ext = pathinfo($filePath)['extension'];
        if ($ext == 'xls') {
            $objReader = IOFactory::createReader('Xls');
        } elseif ($ext == 'xlsx') {
            $objReader = IOFactory::createReader('Xlsx');
        } else {
            return $this->renderError('文件格式错误');
        }
        $objReader->setReadDataOnly(true);
        $spreadSheet = $objReader->load($filePath);
        $sheet       = $spreadSheet->getActiveSheet();
        $rows        = $sheet->toArray();
        if (count($rows) < 1) {
            return $this->renderError('无数据');
        }
        unset($rows[0]);
        $successRow = 0;
        foreach ($rows as $row) {
            if (empty($row[0])) {
                continue;
            }
            if(empty($row[2])){
                $this->renderError('文件内容结构错误，请参考模板');
            }
            $category_id = CategoryModel::where('name', $row[2])->value('category_id', '');
            try {
                $model = new GoodsModel();
                $res   = $model->add([
                    'categoryIds'       => [$category_id],
                    'imagesIds'         => [$row[0]],
                    'goods_name'        => $row[1],
                    'goods_no'          => $row[3],
                    'goods_price'       => $row[4],
                    'cost_price'        => $row[5],
                    'stock_num'         => $row[6],
                    'spec_type'         => 10,
                    'serviceIds'        => [10001, 10003],
                    'deduct_stock_type' => 10,
                    'delivery_id'       => 10001,
                    'goods_weight'      => 0,
                    'status'            => 20,
                    'is_enable_grade'   => 0,
                    'sort'              => 100,
                    'is_alone_grade'    => 0
                ]);
                if ($res) {
                    $successRow++;
                } else {
                    return $this->renderError($model->getError());
                }
            } catch (\Exception $e) {
                throw new Exception($e->getMessage());
            }
        }
        return $this->renderSuccess([], '导入成功' . $successRow . '失败' . (count($rows) - $successRow));
    }
}
